package org.hamster.multidropbox.mainView.model
{
	import org.hamster.dropbox.DropboxClient;
	import org.hamster.dropbox.DropboxEvent;
	import org.hamster.dropbox.models.DropboxFile;
	import org.hamster.multidropbox.dropbox.service.DropboxTreeCacheService;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxClient;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxFile;
	import org.hamster.multidropbox.main.utils.PureMVCHelper;
	import org.hamster.multidropbox.mainView.event.AppFileEvent;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	public class MainViewFileProxy extends Proxy
	{
		public static const NAME:String = "org.hamster.multidropbox.mainView.model.MainViewFileProxy";
		
		public function MainViewFileProxy(data:Object=null)
		{
			super(NAME, data);
		}
		
		public function getFileOrPath(uid:int, path:String):void
		{
			var result:AppDropboxFile = DropboxTreeCacheService.instance.getDropboxItem(uid, path);
			if (result == null) {
				var dropboxClient:DropboxClient = PureMVCHelper.dropboxClientListProxy.getClientByUID(uid);
				
			} else {
				this.sendNotification(AppFileEvent.FILE_PATH_CHANGE_RESULT, result);
			}
		}
		
		private function metadataResultHandler(event:DropboxEvent):void
		{
			var dropboxClient:AppDropboxClient = event.currentTarget as AppDropboxClient;
			var dropboxFile:DropboxFile = event.resultObject as DropboxFile;
			dropboxClient.removeEventListener(DropboxEvent.METADATA_RESULT, metadataResultHandler);
			dropboxClient.removeEventListener(DropboxEvent.METADATA_FAULT,  metadataFaultHandler);
			var file:AppDropboxFile = DropboxTreeCacheService.instance.getDropboxItem(
				dropboxClient.uid, dropboxFile.path);
			sendNotification(AppFileEvent.FILE_PATH_CHANGE_RESULT, file);
		}
		
		private function metadataFaultHandler(event:DropboxEvent):void
		{
			var dropboxClient:AppDropboxClient = event.currentTarget as AppDropboxClient;
			dropboxClient.removeEventListener(DropboxEvent.METADATA_RESULT, metadataResultHandler);
			dropboxClient.removeEventListener(DropboxEvent.METADATA_FAULT,  metadataFaultHandler);
			sendNotification(AppFileEvent.FILE_PATH_CHANGE_FAULT, null);
		}
	}
}